import { isPlainObject, deepMerge } from "./util"
import { Method } from '../types'

// 处理 Content-Type 大小写
function normalizeHeaderName (headers: any, normalizedName: string): void {
    // is headers 是否存在
    if(!headers){
        return
    }
    Object.keys(headers).forEach(name => {
        // is header name 是否相同
      if(name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()){
          // 替换 大写的name
        headers[normalizedName] = headers[name]
        delete headers[name]
      }  
       
    })
}
// 处理 Content-Type 类型
export function processHeaders (headers: any, data: any): any {
    normalizeHeaderName(headers,'Content-Type')
    // is data 是否是普通对象
    if(isPlainObject(data)){
      if (headers && !headers['Content-Type']) {
        headers['Content-Type'] = 'application/json;charset=utf-8'
      }
    }
    return headers
}


// 处理 响应 headers
export function parseHeaders(headers: string): any {
    let parsed = Object.create(null)
    if (!headers) {
      return parsed
    }
  
    headers.split('\r\n').forEach(line => {
      let [key, ...vals] = line.split(':')
      key = key.trim().toLowerCase()
      if (!key) {
        return
      }
      let val = vals.join(':').trim()
      parsed[key] = val
    })

    return parsed
  }


  export function flattenHeaders(headers: any, method: Method): any {
    if (!headers) {
      return headers
    }
    headers = deepMerge(headers.common || {}, headers[method] || {}, headers)
  
    const methodsToDelete = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch', 'common']
  
    methodsToDelete.forEach(method => {
      delete headers[method]
    })
  
    return headers
  }
